package edu.usx.server.config;

import edu.usx.server.pojo.CharUtil;
import edu.usx.server.pojo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.IdentityHashMap;
import java.util.Map;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Name;


@Repository
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    //发件人邮箱
    @Value("${spring.mail.username}")
    private String from;

    private static final String context1 = "<!DOCTYPE html>\n" +
            "<html lang=\"zh-CN\">\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <title>邮件验证码</title>\n" +
            "    <style>\n" +
            "        body {\n" +
            "            font-family: Arial, sans-serif;\n" +
            "            background-color: #f4f4f4;\n" +
            "            margin: 0;\n" +
            "            padding: 0;\n" +
            "        }\n" +
            "        .container {\n" +
            "            max-width: 600px;\n" +
            "            margin: 20px auto;\n" +
            "            background-color: #fff;\n" +
            "            padding: 20px;\n" +
            "            border-radius: 8px;\n" +
            "            box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n" +
            "        }\n" +
            "        h1 {\n" +
            "            color: #333;\n" +
            "            font-size: 24px;\n" +
            "            margin-top: 0;\n" +
            "        }\n" +
            "        p {\n" +
            "            color: #666;\n" +
            "            line-height: 1.6;\n" +
            "        }\n" +
            "        .verification-code {\n" +
            "            font-size: 24px;\n" +
            "            font-weight: bold;\n" +
            "            color: #333;\n" +
            "        }\n" +
            "        .footer {\n" +
            "            margin-top: 20px;\n" +
            "            color: #999;\n" +
            "            font-size: 14px;\n" +
            "        }\n" +
            "        .end {\n" +
            "            margin-top: 20px; \n" +
            "            text-align: right;\n" +
            "        }\n" +
            "    </style>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <div class=\"container\">\n" +
            "        <h1>您的验证码</h1>\n" +
            "        <p>尊敬的用户，您好！</p>\n" +
            "        <p>您的验证码为：<span class=\"verification-code\">";

            private static final String context2= "</span>。请在10分钟内输入验证码完成验证。</p>\n" +
                    "        <p>若非本人操作，请忽略此邮件。</p>\n" +
                    "        <div class=\"footer\">\n" +
                    "            <p>此邮件由系统自动发送，请勿回复。</p>\n" +
                    "            <p class='end'>——USX服务平台</p>\n" +
                    "        </div>\n" +
                    "    </div>\n" +
                    "</body>\n" +
                    "</html>";

    @Async//异步
    public RespBean sendEmailCode(@RequestParam String email, HttpServletRequest request){
        Map<String, Object> map = new IdentityHashMap<>();
        // 获取随机6位验证码
        String verify = CharUtil.randomVerify();
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        //判断邮箱格式/是否存在
        if((!email.matches("^(?!\\.)(?!.*\\.\\.)(?!.*\\.$)[a-zA-Z0-9._%+-]+@((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\\.){1,8}[a-zA-Z]{2,}$"))){
            return RespBean.error("邮箱格式不正确");
        }
        //判断邮箱域名是否存在，速度较慢
//        else if(!hasMXRecord(email.substring(email.indexOf("@")+1))){
//            return RespBean.error("邮箱不存在");
//        }
        try {
            //html为true，表示内容为html格式
            helper = new MimeMessageHelper(message, true);
            // 发送邮箱
            helper.setFrom(from);
            // 接收邮箱
            helper.setTo(email);
            // 标题
            helper.setSubject("usx-邮箱验证");
            // 内容
            helper.setText(context1+verify+context2,true);
            // 发送邮件
            mailSender.send(message);
            map.put("email", email);
            map.put("verify", verify);
            map.put("time", System.currentTimeMillis());
            request.getSession().setMaxInactiveInterval(10*60);
            request.getSession().setAttribute("verify", verify);
            request.getSession().setAttribute("email", email);
            return RespBean.success("验证码发送成功", map);
        } catch (MessagingException e) {
            return RespBean.error("验证码发送失败");
        }
    }

    public static boolean hasMXRecord(String domain) {
        try {
            Lookup lookup = new Lookup(new Name(domain), Type.MX);
            Record[] records = lookup.run();
            if (records != null && records.length > 0) {
                for (Record record : records) {
                    if (record instanceof MXRecord) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Error looking up MX record for domain: " + domain + e);
        }
        return false;
    }
}
